﻿using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_DTO.CommonModels;
using Ekton_Manage_DTO.RequestModels.SysRolePermission;
using Ekton_Manage_DTO.RequestModels.User;
using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Common;
using Ekton_Manage_InfrastructureCore.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using static Ekton_Manage_DTO.CommonModels.DtoFileModel;

namespace Ekton_Manage_Web.Controllers
{
    /// <summary>
    /// 系统设置
    /// </summary>
    /// 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize("Permission")]
    public class SysController : ControllerBase
    {
        private readonly ISelectSysUser _selectSysUser;
        private readonly IBaseRepository<sys_user, int> _basesysuserRepository;
        private readonly IBaseRepository<system_log, int> _basesystemlogRepository;
        public SysController(ISelectSysUser selectSysUser,
            IBaseRepository<sys_user, int> basesysuserRepository, IBaseRepository<system_log, int> basesystemlogRepository)
        {
            _selectSysUser = selectSysUser;
            _basesysuserRepository = basesysuserRepository;
            _basesystemlogRepository = basesystemlogRepository;
        }

        /// <summary>
        /// 菜单动态路由
        /// </summary>
        /// 
        [HttpPost]
        public async Task<Message> GetMenuRouter(int id)
        {
            var userInfo = await _basesysuserRepository.QuerySingleData(m => m.id == id);
            if (userInfo == null)
                return new Message("用户不存在!", false, 202);
            return new Message(await _selectSysUser.GetMenuRouter(id, userInfo.role));
        }

        /// <summary>
        /// 查询菜单结构
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Message> GetMenuList(int id)
        {
            return new Message(await _selectSysUser.GetMenuList(id));
        }
        /// <summary>
        /// 获取选中的菜单权限
        /// </summary>
        /// 
        [HttpPost]
        public async Task<object> GetMenuPower(int roleId)
        {
            return new Message(await _selectSysUser.GetMenuPower(roleId));
        }

        /// <summary>
        /// 查询按钮url
        /// </summary>
        /// 
        [HttpPost]
        public Task<Message> GetBtnRouter()
        {
            return _selectSysUser.GetBtnRouter();
        }

        /// <summary>
        /// 查询全部操作日志
        /// </summary>
        /// 
        [HttpGet]
        public async Task<MessageModel<PageModel<system_log>>> GetSysLogList([FromQuery] QueryDataParame query)
        {
            var result = await _selectSysUser.GetSysLogList(query);
            return new MessageModel<PageModel<system_log>>
            {
                msg = "数据获取成功",
                response = new PageModel<system_log>
                {
                    pageIndex = query.pageIndex,
                    pageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(result.Item2) / query.pageSize)),
                    dataCount = result.Item2,
                    pageSize = query.pageSize,
                    data = result.Item1
                }
            };
        }

        /// <summary>
        /// 查询全部账号
        /// </summary>
        /// 
        [HttpGet]
        public async Task<MessageModel<PageModel<user_roleView>>> GetSysUserList([FromQuery] QueryDataParame query)
        {
            var result = await _selectSysUser.GetSysUserList(query);
            
            return new MessageModel<PageModel<user_roleView>>
            {
                msg = "数据获取成功",
                response = new PageModel<user_roleView>
                {
                    pageIndex = query.pageIndex,
                    pageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(result.Item2) / query.pageSize)),
                    dataCount = result.Item2,
                    pageSize = query.pageSize,
                    data = result.Item1
                }
            };
        }

        /// <summary>
        /// 查询角色信息
        /// </summary>
        /// 
        [HttpGet]
        public async Task<MessageModel<PageModel<sys_role>>> GetSysRolesInfo([FromQuery] QueryDataParame query)
        {
            var result = await _selectSysUser.GetSysRolesInfo(query);
            return new MessageModel<PageModel<sys_role>>
            {
                msg = "数据获取成功",
                response = new PageModel<sys_role>
                {
                    pageIndex = query.pageIndex,
                    pageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(result.Item2) / query.pageSize)),
                    dataCount = result.Item2,
                    pageSize = query.pageSize,
                    data = result.Item1

                }
            };
        }

        /// <summary>
        /// 编辑账号信息
        /// </summary>
        /// 
        [HttpPut]
        public async Task<Message> PutSysUserInfo([FromBody] DtoInsertSysUser query)
        {
            return await _selectSysUser.PutSysUserInfo(query);
        }

        /// <summary>
        /// 停用账号
        /// </summary>
        /// 
        [HttpPut]
        public async Task<Message> PutSysUserState(int userId)
        {
            return await _selectSysUser.PutSysUserState(userId);
        }

        /// <summary>
        /// 删除用户账号
        /// </summary>
        /// 
        [HttpDelete]
        public async Task<Message> DeleteSysUserInfo(int userId) 
        {
            return await _selectSysUser.DeleteSysUserInfo(userId);
        }

        /// <summary>
        /// 重置账号密码
        /// </summary>
        /// 
        [HttpPut]
        public async Task<Message> PutSysUserPwd(int userId)
        {
            return await _selectSysUser.PutSysUserPwd(userId);
        }


        /// <summary>
        /// 编辑角色信息
        /// </summary>
        /// 
        [HttpPut]
        public async Task<Message> PutSysRolesInfo([FromBody] DtoInsertSysRole query)
        {
            return await _selectSysUser.PutSysRolesInfo(query);
        }


        /// <summary>
        /// 修改角色权限（用数组的形式传权限菜单的id,先删除全部菜单id,再添加菜单id）
        /// </summary>
        /// 
        [HttpPost]
        public async Task<Message> PostSysUserPower([FromBody] DtoSysUserPower request)
        {
            return await _selectSysUser.PostSysUserPower(request);
        }


        /// <summary>
        /// 添加角色信息
        /// </summary>
        /// 
        [HttpPost]
        public async Task<Message> PostSysRolesInfo([FromBody] DtoInsertSysRole query)
        {
            return await _selectSysUser.PostSysRolesInfo(query);
        }

        /// <summary>
        /// 添加账号信息
        /// </summary>
        /// 
        [HttpPost]
        public async Task<Message> PostSysUserInfo([FromBody] DtoInsertSysUser request)
        {
            var account = await _basesysuserRepository.QuerySingleData(m => m.account == request.account);
            if (account == null)
            {
                return await _selectSysUser.PostSysUserInfo(request);
            }
            return new Message("该用户名已被注册!", false, 202);
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// 
        [HttpDelete]
        public async Task<Message> DeleteSysRolesInfo(int id)
        {
            return await _selectSysUser.DeleteSysRolesInfo(id);
        }

        /// <summary>
        /// 导出操作日志
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<FileResult> systemLogExportData([FromBody] ExportFormData formData)
        {
            List<system_log> data = new();
            if (formData.list.Count < 1)
                data = await _basesystemlogRepository.QueryTableList(m => true);
            else
                data = await _basesystemlogRepository.QueryTableList(m => formData.list.Contains(m.id)); 

            //创建一个新的excel文件
            HSSFWorkbook book = new HSSFWorkbook();
            //创建一个工作区
            ISheet sheet = book.CreateSheet("sheet1");
            //创建一行
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < 5; i++)
            {
                sheet.SetColumnWidth(i, 23 * 156);
            }
            sheet.SetColumnWidth(4, 30 * 156);
            sheet.SetColumnWidth(1, 21 * 156);
            //定义一个样式
            ICellStyle setborder = book.CreateCellStyle();
            setborder.BorderLeft = BorderStyle.Thin;
            setborder.BorderRight = BorderStyle.Thin;
            setborder.BorderBottom = BorderStyle.Thin;
            setborder.BorderTop = BorderStyle.Thin;

            //文字水平和垂直对齐方式
            setborder.VerticalAlignment = VerticalAlignment.Center;//垂直居中
            setborder.Alignment = HorizontalAlignment.Center;//水平居中
            setborder.WrapText = true;//自动换行

            //再定义一个样式，用来设置最上面标题行的样式
            ICellStyle setborderdeth = book.CreateCellStyle();
            setborderdeth.BorderLeft = BorderStyle.Thin;
            setborderdeth.BorderRight = BorderStyle.Thin;
            setborderdeth.BorderBottom = BorderStyle.Thin;
            setborderdeth.BorderTop = BorderStyle.Thin;

            //定义一个字体样式
            IFont font = book.CreateFont();
            //将字体设为红色
            font.Color = IndexedColors.Red.Index;
            setborderdeth.SetFont(font);
            setborderdeth.VerticalAlignment = VerticalAlignment.Center;
            setborderdeth.Alignment = HorizontalAlignment.Center;
            setborderdeth.WrapText = true;

            row.HeightInPoints = 25;
            //设置单元格的值
            row.CreateCell(0).SetCellValue("序号");
            row.GetCell(0).CellStyle = setborderdeth;
            row.CreateCell(1).SetCellValue("创建人");
            row.GetCell(1).CellStyle = setborderdeth;
            row.CreateCell(2).SetCellValue("IP地址");
            row.GetCell(2).CellStyle = setborderdeth;
            row.CreateCell(3).SetCellValue("操作类型");
            row.GetCell(3).CellStyle = setborderdeth;
            row.CreateCell(4).SetCellValue("操作描述");
            row.GetCell(4).CellStyle = setborderdeth;
            row.CreateCell(5).SetCellValue("操作时间");
            row.GetCell(5).CellStyle = setborderdeth;
            for (int i = 0; i < data.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                row1.HeightInPoints = 21;
                row1.CreateCell(0).SetCellValue(i);
                row1.GetCell(0).CellStyle = setborder;
                row1.CreateCell(1).SetCellValue(Convert.ToString(data[i].create_op_name));
                row1.GetCell(1).CellStyle = setborder;
                row1.CreateCell(2).SetCellValue(Convert.ToString(data[i].ip_address));
                row1.GetCell(2).CellStyle = setborder;
                row1.CreateCell(3).SetCellValue(Convert.ToString(data[i].oper_type));
                row1.GetCell(3).CellStyle = setborder;
                row1.CreateCell(4).SetCellValue(Convert.ToString(data[i].oper_describe));
                row1.GetCell(4).CellStyle = setborder;
                row1.CreateCell(5).SetCellValue(Convert.ToString(data[i].create_op_date));
                row1.GetCell(5).CellStyle = setborder;
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            DateTime dttime = DateTime.Now;
            string datetime = dttime.ToString("yyyy-MM-dd");
            string filename = "操作日志导出" + datetime + ".xls";
            return File(ms, "application/vns.ms-excel", filename);
        }

        /// <summary>
        /// 导出账号管理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<FileResult> sysUserExportData([FromBody] ExportFormData formData)
        {
            List<sys_user> data = new();
            if (formData.list.Count < 1)
                data = await _basesysuserRepository.QueryTableList(m => true);
            else
                data = await _basesysuserRepository.QueryTableList(m => formData.list.Contains(m.id)); 

            //创建一个新的excel文件
            HSSFWorkbook book = new HSSFWorkbook();
            //创建一个工作区
            ISheet sheet = book.CreateSheet("sheet1");
            //创建一行
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < 8; i++)
            {
                sheet.SetColumnWidth(i, 23 * 156);
            }
            sheet.SetColumnWidth(4, 30 * 156);
            sheet.SetColumnWidth(1, 21 * 156);
            //定义一个样式
            ICellStyle setborder = book.CreateCellStyle();
            setborder.BorderLeft = BorderStyle.Thin;
            setborder.BorderRight = BorderStyle.Thin;
            setborder.BorderBottom = BorderStyle.Thin;
            setborder.BorderTop = BorderStyle.Thin;

            //文字水平和垂直对齐方式
            setborder.VerticalAlignment = VerticalAlignment.Center;//垂直居中
            setborder.Alignment = HorizontalAlignment.Center;//水平居中
            setborder.WrapText = true;//自动换行

            //再定义一个样式，用来设置最上面标题行的样式
            ICellStyle setborderdeth = book.CreateCellStyle();
            setborderdeth.BorderLeft = BorderStyle.Thin;
            setborderdeth.BorderRight = BorderStyle.Thin;
            setborderdeth.BorderBottom = BorderStyle.Thin;
            setborderdeth.BorderTop = BorderStyle.Thin;

            //定义一个字体样式
            IFont font = book.CreateFont();
            //将字体设为红色
            font.Color = IndexedColors.Red.Index;
            setborderdeth.SetFont(font);
            setborderdeth.VerticalAlignment = VerticalAlignment.Center;
            setborderdeth.Alignment = HorizontalAlignment.Center;
            setborderdeth.WrapText = true;

            row.HeightInPoints = 25;
            //设置单元格的值
            row.CreateCell(0).SetCellValue("序号");
            row.GetCell(0).CellStyle = setborderdeth;
            row.CreateCell(1).SetCellValue("用户账号");
            row.GetCell(1).CellStyle = setborderdeth;
            row.CreateCell(2).SetCellValue("姓名");
            row.GetCell(2).CellStyle = setborderdeth;
            row.CreateCell(3).SetCellValue("手机号");
            row.GetCell(3).CellStyle = setborderdeth;
            row.CreateCell(4).SetCellValue("所属公司组织");
            row.GetCell(4).CellStyle = setborderdeth;
            row.CreateCell(5).SetCellValue("角色");
            row.GetCell(5).CellStyle = setborderdeth;
            row.CreateCell(6).SetCellValue("状态");
            row.GetCell(6).CellStyle = setborderdeth;
            row.CreateCell(7).SetCellValue("创建人");
            row.GetCell(7).CellStyle = setborderdeth;
            row.CreateCell(8).SetCellValue("创建时间");
            row.GetCell(8).CellStyle = setborderdeth;
            for (int i = 0; i < data.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                row1.HeightInPoints = 21;
                row1.CreateCell(0).SetCellValue(i);
                row1.GetCell(0).CellStyle = setborder;
                row1.CreateCell(1).SetCellValue(Convert.ToString(data[i].account));
                row1.GetCell(1).CellStyle = setborder;
                row1.CreateCell(2).SetCellValue(Convert.ToString(data[i].name));
                row1.GetCell(2).CellStyle = setborder;
                row1.CreateCell(3).SetCellValue(Convert.ToString(data[i].phone));
                row1.GetCell(3).CellStyle = setborder;
                row1.CreateCell(4).SetCellValue(Convert.ToString(data[i].company));
                row1.GetCell(4).CellStyle = setborder;
                row1.CreateCell(5).SetCellValue(Convert.ToString(data[i].role_name));
                row1.GetCell(5).CellStyle = setborder;
                row1.CreateCell(6).SetCellValue(Convert.ToString(data[i].state));
                row1.GetCell(6).CellStyle = setborder;
                row1.CreateCell(7).SetCellValue(Convert.ToString(data[i].create_op_name));
                row1.GetCell(7).CellStyle = setborder;
                row1.CreateCell(8).SetCellValue(Convert.ToString(data[i].create_op_date));
                row1.GetCell(8).CellStyle = setborder;
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            DateTime dttime = DateTime.Now;
            string datetime = dttime.ToString("yyyy-MM-dd");
            string filename = "账号管理导出" + datetime + ".xls";
            return File(ms, "application/vns.ms-excel", filename);
        }

        /// <summary>
        /// 公司邮箱配置(通过平台id来修改公司邮箱)
        /// </summary>
        [HttpPut]
        public async Task<Message> PostCompanyEmail(int platform_id, string email,string auth_code)
        {
            return await _selectSysUser.PostCompanyEmail(platform_id, email, auth_code);
        }

        /// <summary>
        /// 通过平台id来查询公司邮箱
        /// </summary>
        /// <param name="platform_id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Message> GetCompanyEmail(int platform_id)
        {
            return await _selectSysUser.GetCompanyEmail(platform_id);
        }

        /// <summary>
        /// 查看底部版权栏信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Message> GetCopyRight()
        {
            return await _selectSysUser.GetCopyRight();
        }

        /// <summary>
        /// 修改底部版权蓝信息
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [AllowAnonymous]
        public async Task<Message> PutCopyRight(DtoCopyRight request)
        {
            return await _selectSysUser.PutCopyRight(request);
        }
        /// <summary>
        /// 获取按钮编码
        /// </summary>
        /// <param name="id"></param>s
        /// <remarks>
        /// id为用户的id
        /// </remarks>
        /// <returns></returns>
        /// 
        [HttpGet]
        public async Task<Message> GetBtnCodes(int id)
        {
            return await _selectSysUser.GetBtnCodes(id);
        }
    }
}
